package com.myspring.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * ClassName: ConnectionFactory
 * Package: com.mystring.utils
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/1 17:47
 * @Version 1.0
 */

@Component
public class ConnectionFactory {
    @Autowired
    ThreadLocal<Connection> threadLocal;

    @Autowired
    DataSource dataSource;

    public Connection currentThreadConn() {
        //1.先尝试从ThreadLocal中获取当前线程对应的连接
        Connection connection = threadLocal.get();

        //2.判断当前线程对应的是否有连接
        if (connection == null) {
            try {
                //3.从连接池中获取一个连接
                connection = dataSource.getConnection();
            } catch (SQLException throwables) {
                throw new RuntimeException(throwables.getMessage());

            }
            //4.将连接与当前线程绑定
            threadLocal.set(connection);
        }

        //返回连接
        return connection;
    }
}
